<template>
  <div class="forgot-password">
    <div class="container">
      <div class="field"><h1>忘记密码</h1></div>
      <!-- 步骤指示器 -->
      <div class="step-indicator">
        <span
          :class="{ active: step === 1 }"
          @click="handleStepClick(1)"
        >1. 验证邮箱</span>
        <span
          :class="{ active: step === 2, disabled: !hasReachedStep2 }"
          @click="handleStepClick(2)"
        >2. 修改密码</span>
      </div>
      <div
  class="message-box"
  :class="messageType"
  v-if="showMessage"
>
  {{ messageText }}
</div>


      <!-- 步骤一：邮箱验证 -->
      <template v-if="step === 1">
        <input
          v-model="email"
          type="email"
          placeholder="请输入注册时使用的邮箱"
          class="input-box"
        />
        <button @click="handleNextStep" class="btn-next">下一步</button>
      </template>

      <!-- 步骤二：密码重置 -->
      <template v-else-if="step === 2">
        <div class="code-input-container">
          <input
            v-model="verificationCode"
            type="text"
            placeholder="请输入验证码"
            class="input-box small-input"
          />
          <button
            @click="handleSendCode"
            :disabled="countdown > 0"
            class="btn-send-code"
          >
            {{ countdown > 0 ? `${countdown}s后重发` : '发送验证码' }}
          </button>
        </div>

        <input
          v-model="newPassword"
          type="password"
          placeholder="输入新密码"
          class="input-box"
        />

        <button @click="handleResetPassword" :disabled="isLoading" class="btn-next">{{ isLoading ? '重置中...' : '重置密码' }}</button>
      </template>
    </div>
  </div>
</template>

<script setup>
const router = useRouter()

// 添加消息提示状态
const showMessage = ref(false)
const messageText = ref('')
const messageType = ref('info')
// 响应式状态
const step = ref(1)
const email = ref('')
const verificationCode = ref('')
const newPassword = ref('')
const countdown = ref(0)
const hasReachedStep2 = ref(false)
const isLoading = ref(false)

// 定时器引用
let timer = null

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) clearInterval(timer)
})

// 步骤切换处理
const handleStepClick = (stepNumber) => {
  if (stepNumber === 2 && !hasReachedStep2.value) return
  step.value = stepNumber
}
// 显示消息的方法
const showAlert = (text, type = 'info') => {
  messageText.value = text
  messageType.value = type
  showMessage.value = true
  setTimeout(() => {
    showMessage.value = false
  }, 3000)
}
// 邮箱验证
const validateEmail = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!email.value) {
    showAlert('请输入邮箱地址', 'warning')
    return false
  }
  if (!emailRegex.test(email.value)) {
    showAlert('邮箱格式不正确', 'warning')
    return false
  }
  return true
}

// 下一步处理
const handleNextStep = async () => {
  if (!validateEmail()) return

  try {
    isLoading.value = true
    const response = await axios.post('/api/accounts/send_verification_code/', {
      email: email.value
    })

    if (response.status === 200) {
      showAlert('验证码已发送，请注意查收邮箱', 'success')
      hasReachedStep2.value = true
      step.value = 2
      startCountdown()
    } else {
      showAlert(response.data.message || '邮件发送失败', 'error')
    }
  } catch (error) {
    showAlert('请求失败，请检查网络', 'error')
  } finally {
    isLoading.value = false
  }
}

// 发送验证码
const handleSendCode = async () => {
  if (countdown.value > 0) return
  if (!validateEmail()) return

  try {
    const response = await axios.post('/api/accounts/send_verification_code/', {
      email: email.value
    })

    if (response.status === 200) {
      showAlert('验证码已发送', 'info')

      startCountdown()
    } else {
      showAlert(response.data.message || '验证码发送失败', 'error')
    }
  } catch (error) {
    showAlert('请求失败，请检查网络', 'error')
  }
}

// 密码强度验证
const validatePassword = (password) => {
  const strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/
  return strongRegex.test(password)
}

// 重置密码
const handleResetPassword = async () => {
  if (!verificationCode.value) {
    showAlert('请输入验证码', 'warning')
    return
  }

  if (!validatePassword(newPassword.value)) {
    showAlert('密码必须包含大小写字母和数字，长度8-16位', 'warning')
    return
  }

  try {
    isLoading.value = true
    const response = await axios.post('/api/accounts/reset_password/', {
      email: email.value,
      code: verificationCode.value,
      new_password: newPassword.value
    })

    if (response.status === 200) {
      showAlert('密码重置成功', 'info')
      // 重置表单
      step.value = 1
      email.value = ''
      verificationCode.value = ''
      newPassword.value = ''
      hasReachedStep2.value = false
      router.push('/login')
    } else {
      showAlert(response.data.message || '密码重置失败', 'error')
    }
  } catch (error) {
    showAlert('密码重置失败，请检查邮箱或验证码是否正确', 'error')
  } finally {
    isLoading.value = false
  }
}

// 保持原有倒计时方法
const startCountdown = () => {
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) clearInterval(timer)
  }, 1000)
}
</script>


<style scoped>
.forgot-password {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f4f6f8;
  font-family: "Arial", sans-serif;
  background-image: url('@/assets/accounts/img/forgot_bg.jpg');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  position: relative;
}
.forgot-password::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  z-index: 1;
}
.container {
  background: #ffffff;
  padding: 30px 40px;
  border-radius: 12px;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  width: 350px;
  z-index: 2;
}
.field {
  margin-bottom: 20px;
}
.field h1 {
  font-size: 24px;
  color: #5fb878;
  margin: 0;
}
.step-indicator {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
}
.step-indicator span {
  flex: 1;
  text-align: center;
  padding: 5px 0;
  border-bottom: 2px solid transparent;
}
.step-indicator span.active {
  font-weight: bold;
  color: #5fb878;
  border-color: #5fb878;
}
.subtitle {
  font-size: 14px;
  color: #666;
  margin:20px 0;
}
.input-box {
  width: 100%;
  padding: 12px 15px;
  margin-bottom: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  font-size: 14px;
  box-sizing: border-box;
}
.small-input {
  flex: 1;
   margin-right: 10px;
  height: 40px; /* 保证高度一致 */
}

.input-box:focus {
  border-color: #5fb878;
  outline: none;
  box-shadow: 0px 0px 5px rgba(0, 123, 255, 0.5);
}
.code-input-container {
  display: flex;
  justify-content: space-between;
  align-items: stretch;
}
.btn-next{
  width: 100%;
  flex-shrink: 0; /* 不允许缩小 */
  height: 40px; /* 按钮高度和输入框一致 */
  padding: 12px 15px;
  font-size: 14px;
  background-color: #5fb878;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  box-sizing: border-box;
}
.btn-send-code {
  flex-shrink: 0; /* 不允许缩小 */
  height: 40px; /* 按钮高度和输入框一致 */
  padding: 12px 15px;
  font-size: 14px;
  background-color: #5fb878;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  box-sizing: border-box;
}
.btn-next:hover,
.btn-send-code:hover {
  background: linear-gradient(to right, #75e178, #00bfae);
}
.btn-next:disabled {
  background: #cccccc;
  cursor: not-allowed;
}
.btn-send-code:disabled {
  background: #ccc;
  cursor: not-allowed;
}
.message-box {
  margin-bottom: 20px;
  font-size: 14px;
  padding: 12px;
  border-radius: 6px;
  text-align: center;
}

/* 信息类型 - 蓝色 */
.message-box.info {
  color: #0080ff;
}

/* 成功类型 - 绿色 */
.message-box.success {
  color: #5FB878;
}

/* 警告类型 - 橙色 */
.message-box.warning {
  color: #eb8517;
}

/* 错误类型 - 红色 */
.message-box.error {
  color: red;
}


</style>
